package com.patterns.demo.flyWeight;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Author: SamGroves
 * <p>
 * Description: 将所有对象放到一个map中 当作是池
 *
 *      查找共享对象的时候 没有则创建一个 有则直接返回
 * <p>
 * Date: 2017/12/4
 */
public class FlyWeightFactory {

    private static ConcurrentHashMap<String, FlyWeight> allFlyWeight = new ConcurrentHashMap<>();

    public static FlyWeight getFlyWeight(String name) {
        if (allFlyWeight.get(name) == null) {
            synchronized (allFlyWeight) {
                if (allFlyWeight.get(name) == null) {
                    System.out.println("this object do not exist, so we created one!");
                    FlyWeight flyWeight = new ConcreteFlyWeight(name);
                    flyWeight.action();
                    allFlyWeight.put(name, flyWeight);
                }
            }
        }
        return allFlyWeight.get(name);
    }
}
